<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NPagination, NButton, NModal, NForm, NFormItem, NInput, useMessage } from 'naive-ui';
import { getGroupList, createGroup, updateGroup, deleteGroup, getGroupDetail } from '#/api/authserver/group';

const columns = [
  { key: 'id', title: '群组ID' },
  { key: 'name', title: '群组名称' },
  { key: 'type', title: '群组类型' },
  { key: 'description', title: '描述' },
  { key: 'parentId', title: '父群组ID' },
  { key: 'path', title: '路径' },
  { key: 'createdAt', title: '创建时间' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const message = useMessage();

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'>('create');
const modalTitle = ref('');
const formModel = ref<any>({});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getGroupList({ page: page.value, size: pageSize.value });
    data.value = res.result?.items || [];
    total.value = res.result?.total || 0;
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handlePageChange(p: number) {
  page.value = p;
  fetchData();
}

function handlePageSizeChange(s: number) {
  pageSize.value = s;
  page.value = 1;
  fetchData();
}

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建群组';
  formModel.value = {};
  showModal.value = true;
}

function handleEdit(row: any) {
  modalType.value = 'edit';
  modalTitle.value = '编辑群组';
  formModel.value = { ...row };
  showModal.value = true;
}

async function handleDetail(row: any) {
  modalType.value = 'detail';
  modalTitle.value = '群组详情';
  formLoading.value = true;
  try {
    const res = await getGroupDetail(row.id);
    formModel.value = res.result || {};

    // 转换为表格数据格式
    detailData.value = [
      { field: '群组ID', value: formModel.value.id || '-' },
      { field: '群组名称', value: formModel.value.name || '-' },
      { field: '群组类型', value: formModel.value.type || '-' },
      { field: '描述', value: formModel.value.description || '-' },
      { field: '父群组ID', value: formModel.value.parentId || '-' },
      { field: '路径', value: formModel.value.path || '-' },
      { field: '创建时间', value: formModel.value.createdAt || '-' },
      { field: '创建者', value: formModel.value.createdBy || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}

async function handleDelete(row: any) {
  if (confirm('确定要删除该群组吗？')) {
    try {
      await deleteGroup(row.id);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    if (modalType.value === 'create') {
      await createGroup(formModel.value);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      await updateGroup(formModel.value.id, formModel.value);
      message.success('编辑成功');
    }
    showModal.value = false;
    fetchData();
  } catch (error) {
    message.error(modalType.value === 'create' ? '新建失败' : '编辑失败');
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="群组管理" title="群组管理">
    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建群组</NButton>
    </div>
    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <div class="mt-4 flex justify-end">
      <NPagination
        v-model:page="page"
        v-model:page-size="pageSize"
        :item-count="total"
        show-size-picker
        :page-sizes="[10, 20, 50, 100]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>
    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '800px' }">
      <NForm :model="formModel" label-width="100" v-if="modalType !== 'detail'">
        <NFormItem label="群组名称" path="name">
          <NInput v-model:value="formModel.name" />
        </NFormItem>
        <NFormItem label="群组类型" path="type">
          <NInput v-model:value="formModel.type" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" />
        </NFormItem>
        <NFormItem label="父群组ID" path="parentId">
          <NInput v-model:value="formModel.parentId" />
        </NFormItem>
      </NForm>
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />
      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
